<template>
  <view class="flex-row flex-wrap">
    <view v-for="(item,index) in list" :key="index" class="upload-item margin-right-40 margin-bottom-30 relative" :style="{width, height}" @click="viewImage(index, list)">
      <image v-if="hasHeader && !index" src="/static/header-corner-mark.png" class="header-corner-mark"/>
      <easy-cacheimage :image-src="item" class="width-full height-full" mode="aspectFill" @click="viewImage(index, list)"/>
      <view v-if="!disabled" class="delete flex-row flex-center" @click.stop="delImage(index)">
        <text class="technician-shanchu1 color-white text-26" />
      </view>
    </view>
    <by-view v-if="list.length < count && !disabled" @click="checkApi">
      <view class="add upload-item flex-column flex-center" :style="{width, height}">
        <text class="technician-jia"></text>
        <text v-if="placeholder" class="text-26 color-t2 margin-top-20">{{ placeholder }}</text>
      </view>
    </by-view>
  </view>

  <by-dialog v-model="showModal" title="提示" content="app需要访问您的相册或相机并选择个人照片，照片将用于入驻审核或资料上传" @confirm="openAuth"/>

  <canvas v-if="watermark" canvas-id="canvas" class="canvas" :style="{width:cWidth + 'px',height:cHeight + 'px'}"/>
</template>

<script setup lang="ts">
import permision from '@/js_sdk/wa-permission/permission.js'
import useSystemStore from '@/store/system'
import uploadFile from '@/common/cos-upload'
import { chooseFile, viewImage, loading } from '@/common/util'
import type { TChooseFileCount } from '@/common/types'
import type { ShallowRef } from 'vue'

interface IProps{
  count: TChooseFileCount
  modelValue: string
  hasHeader: boolean
  watermark: boolean
  disabled: boolean
  width?: string
  height?: string
  placeholder?: string
}

const props = withDefaults(defineProps<IProps>(), {
  count: 6,
  modelValue: '',
  hasHeader: false,
  watermark: false,
  disabled: false
})

watch(() => props.modelValue, initValue)

const $emit = defineEmits(['update:modelValue', 'change'])

const list:ShallowRef<string[]> = shallowRef([])

function initValue(value:string) {
  if (value) list.value = value.split(',')
}
initValue(props.modelValue)

const systemStore = useSystemStore()
const showModal = ref(false)
async function checkApi() {
  /* #ifdef APP-PLUS*/
  const canChooseImage = uni.getStorageSync('technicianCanChooseImage')
  if (!canChooseImage) uni.$emit('showChooseImageTip')
  if (systemStore.systemInfo.platform === 'ios') {
    const isAuth = permision.judgeIosPermission('camera') && permision.judgeIosPermission('photoLibrary')
    if (!isAuth) showModal.value = true
    else handleChooseFile()
  } else {
    const isAuth = await permision.requestAndroidPermission(['android.permission.READ_EXTERNAL_STORAGE', 'android.permission.CAMERA'])
    if (isAuth !== 1) showModal.value = true
    else handleChooseFile()
  }
  /* #endif*/
  /* #ifndef APP-PLUS*/
  handleChooseFile()
  /* #endif*/
}

function openAuth() {
  if (systemStore.systemInfo.platform === 'ios') {
    handleChooseFile()
  } else {
    permision.gotoAppPermissionSetting()
  }
}

async function handleChooseFile() {
  uni.setStorageSync('technicianCanChooseImage', 1)
  uni.$off('showChooseImageTip')
  const count:TChooseFileCount = (props.count - list.value.length) as TChooseFileCount
  const res = await chooseFile(count)
  let num = 0
  const load = loading('上传中...')
  for (let i = 0; i < res.length; i++) {
    const item = res[i]
    const file = {
      name: item.name,
      path: item.path
    }
    // if (props.watermark) file.path = await addWatermark(await compress(item.path))
    uploadFile(file, filePath => {
      console.log(filePath)
      list.value.push(filePath)
      num++
      triggerRef(list)
      if (num === res.length) {
        $emit('update:modelValue', list.value.join(','))
        $emit('change', {
          list: list.value,
          total: list.value.length
        })
        load.hide()
      }
    }, props.watermark ? 'technician-material' : undefined)
  }
}

async function delImage(index:number) {
  list.value.splice(index, 1)
  triggerRef(list)
  $emit('update:modelValue', list.value.join(','))
  $emit('change', {
    list: list.value,
    total: list.value.length
  })
}

const that = getCurrentInstance()
const context = uni.createCanvasContext('canvas', that)
const cWidth = ref(0)
const cHeight = ref(0)
function addWatermark(src:string) {
  return new Promise(resolve => {
    uni.getImageInfo({
      src,
      success: (image) => {
        if (image.width > 1080) {
          image.width = 1080
          image.height = image.height / (image.width / 1080)
        }
        cWidth.value = image.width
        cHeight.value = image.height
        setTimeout(() => {
          // 将图片src放到cancas内，宽高为图片大小
          context.drawImage(src, 0, 0, image.width, image.height)
          context.rotate(45 * Math.PI / 180)
          for (let i = 0; i <= 50; i++) {
            context.beginPath()
            context.setFontSize(50)
            context.setFillStyle('rgba(169,169,169,0.4)')
            context.fillText('技师之家', 0, i * 170)
            for (let j = 0; j <= 50; j++) {
              context.beginPath()
              context.setFontSize(50)
              context.setFillStyle('rgba(169,169,169,0.4)')
              context.fillText('技师之家', j * 340, i * 170)
            }
          }
          for (let i = 0; i < 50; i++) {
            context.beginPath()
            context.setFontSize(50)
            context.setFillStyle('rgba(169,169,169,0.4)')
            context.fillText('技师之家', 0, -170 * i)
            for (let j = 1; j < 50; j++) {
              context.beginPath()
              context.setFontSize(50)
              context.setFillStyle('rgba(169,169,169,0.4)')
              context.fillText('技师之家', 340 * j, -170 * i)
            }
          }
          context.rotate(-45 * Math.PI / 180)
          context.draw(false, () => {
            setTimeout(() => {
              uni.canvasToTempFilePath({
                canvasId: 'canvas',
                fileType: 'jpg',
                success: (path) => {
                  // 压缩
                  console.log(path.tempFilePath)
                  resolve(path.tempFilePath)
                },
                complete: (res) => {
                  console.log(res, '画布生成图片回调')
                }
              }, that)
            }, 1000)
          })
        }, 1000)
      }
    })
  })
}

async function compress(path:string) {
  return new Promise<string>(resolve => {
    /* #ifdef H5*/
    resolve(path)
    /* #endif*/
    /* #ifndef H5*/
    uni.compressImage({
      src: path,
      quality: 20,
      success: res => {
        // console.log(res.tempFilePath)
        resolve(res.tempFilePath)
      },
      complete: (res) => {
        console.log(res, '压缩图片回调')
      }
    })
    /* #endif*/
  })
}
</script>

<style scoped lang="scss">
.upload-item{
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  overflow: hidden;

  &:nth-child(3n){
    margin-right: 0;
  }

  &:first-child:last-child{
    margin-right: 0;
  }

  .header-corner-mark{
    @include position(absolute, 0, 0);
    width: 58rpx;
    height: 56rpx;
  }

  &.add{
    background: $color-border;
    border: 2rpx solid #F3F3F3;
    margin-bottom: 30rpx !important;

    .technician-jia{
      font-size: 72rpx;
      color: #d3d3d3;
    }

  }

  .delete{
    @include position(absolute, $left: 0, $bottom: 0, $z-index:5);
    width: 100%;
    height: 50rpx;
    background: $color-bg-mask;
  }

}
.canvas{
  /*position: fixed;
  //opacity: 0;
  top: 1500%;
  left: 1500%;*/
}
</style>
